package a06_栈与队列;

import java.util.Stack;

/**
 * <p>
 * a05_逆波兰表达式求值
 * </p>
 *
 * @author flyduck
 * @since 2024-08-13
 */
public class a06_逆波兰表达式求值复习1 {

    public static void main(String[] args) {
        System.out.println(evalRPN(new String[]{"4", "13", "5", "/", "+"}));
    }

    public static int evalRPN(String[] tokens) {
        Stack<String> stack = new Stack<>();
        for (String token : tokens) {
            if(token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")){
                Integer num1 = Integer.valueOf(stack.pop());
                Integer num2 = Integer.valueOf(stack.pop());
                switch (token) {
                    case "+":
                        stack.push(String.valueOf(num2 + num1));
                        break;
                    case "-":
                        stack.push(String.valueOf(num2 - num1));
                        break;
                    case "*":
                        stack.push(String.valueOf(num2 * num1));
                        break;
                    case "/":
                        stack.push(String.valueOf(num2 / num1));
                        break;
                }
            }else {
                stack.push(token);
            }
        }
        return Integer.valueOf(stack.pop());
    }
}
